package me.weijing.common.http;

import me.weijing.common.http.NetBroadCastReceiver.NetworkStateListener;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;

public class HttpManager implements NetworkStateListener {
    private static final String INTENT_NETSTATE = "android.net.conn.CONNECTIVITY_CHANGE";
    private static HttpManager httpManager;
    // private ExecutorService mThreadPool;// 启动线程
    protected NetBroadCastReceiver netBroadCastReceiver;
    private int netType;

    private Context context;
    private Handler handler;

    /*
     * private Map<String,String> mExtraHeader=new ConcurrentHashMap<String,
     * String>();
     */

    private HttpManager() {
        handler = new Handler(Looper.getMainLooper());
        // mExtraHeader.put(AZusNetConstant.kHTTPHEADER_USERAGENT,
        // HuPanApplication.getUserAgent());
        // mExtraHeader.put("deviceId", HuPanApplication.getDeviceId());
    }

    public static HttpManager getInstance() {
        if (httpManager == null) {
            httpManager = new HttpManager();
        }
        return httpManager;
    }

    /**
     * 注册网络状的广播
     * 
     * @param context
     *            请务必使用getApplicationContext();
     */
    public void init(final ContextWrapper context) {
        this.context = context;
        if (context != null) {
            if (netBroadCastReceiver == null) {
                netBroadCastReceiver = new NetBroadCastReceiver(this);
            }

            IntentFilter filter = new IntentFilter(INTENT_NETSTATE);
            context.registerReceiver(netBroadCastReceiver, filter);
            handler.post(new Runnable() {

                @Override
                public void run() {
                    
                    setCommuType(netBroadCastReceiver.searchCommuType(context));
                }
            });
        }

        // userAgent = "android.br";
        // deviceId = "#00000";
    }

    @Override
    public void commuTypeChange(int commuType) {
        
        setCommuType(commuType);
    }

    public synchronized int getCommuType() {
        return netType;
    }

    public synchronized void setCommuType(int commuType) {
        this.netType = commuType;
    }

    public void recycle() {
        if (context != null) {
            context.unregisterReceiver(netBroadCastReceiver);
        }
        // if(mThreadPool != null){
        // mThreadPool.shutdown();
        // mThreadPool = null;
        // }
        if (httpManager != null) {
            httpManager = null;
        }
    }
}
